package com.example.websocket.server;// springboot websocket server

import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

@ServerEndpoint("/websocket")
@Component
public class UpdateSeatsServer {

    // 用于存放所有在线客户端
    private static CopyOnWriteArraySet<UpdateSeatsServer> webSocketSet = new CopyOnWriteArraySet<>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        System.out.println("有新的连接，当前在线人数为" + webSocketSet.size());
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        System.out.println("有人离开，当前在线人数为" + webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //接收到的座位信息广播所有
        System.out.println("收到客户端的消息：" + message);
        // 群发消息
        for (UpdateSeatsServer chatServer : webSocketSet) {
            try {
                chatServer.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    // 锁座
//    public static String addBillSessionSeats(String curSessionSeats, Map<String, Integer> selectedSeatsMap) {
//        JSONObject curSessionSeatsJSON = JSONObject.parseObject(curSessionSeats);
//        Map<String, Object> valueMap = new LinkedHashMap<>();
//        valueMap.putAll(curSessionSeatsJSON);
//        valueMap.forEach((key, value) -> System.out.println("\"" + key + "\":" + "   " + value));
//        // 选座
//        selectedSeatsMap.forEach((index, value) -> {
//            ((JSONArray) valueMap.get(index)).set(value - 1, 0);
//        });
//        JSONObject newSessionSeatsJSON = new JSONObject(valueMap);
//        return JSONObject.toJSONString(newSessionSeatsJSON);
//    }
}